const express = require('express')

const articleRouter = express.Router()
const { articleModel, ratingsModel } = require('../model/articleSchema')
const passport = require('passport')
const handleTime = require('../utils/formatTime')


//发布文章
articleRouter.post('/saveArticle', passport.authenticate('jwt', { session: false }), async(req, res) => {
    let { classify, title, content } = req.body

    let saveStatus = await articleModel.create({
        classify,
        title,
        content,
        userInfo: req.user._id,
        isAdmin: req.user.identity == 0
    })

    if (saveStatus) {
        res.send({ code: 0, msg: 'success' })
    }
})

//文章初始化 分页制作 前端分类切换 查询
articleRouter.get('/articleList', async(req, res) => {
    let { page = 0, classify = null, size = 3, searchValue } = req.query

    let base_query_obj = { isAdmin: false }
    let admin_query_obj = { isAdmin: true }

    if (classify && classify != 0) {
        base_query_obj.classify = classify
        admin_query_obj.classify = classify
    }

    if (searchValue) {
        base_query_obj.title = new RegExp(searchValue)
        admin_query_obj.title = new RegExp(searchValue)
    }

    //获取普通用户所有数据相关数据值+关联表数据值
    let searchResult = await articleModel.find(base_query_obj, {
            content: 0
        })
        .populate({
            path: `ratings`,
            select: 'date avatar',
            options: { limit: 1, sort: { _id: -1 } }
        })
        .populate({
            path: "userInfo",
            select: 'avatar'
        }).skip(+page * +size).limit(+size).sort({ '_id': -1 })


    //获取普通用户所有的数据值总是
    let total = await articleModel.countDocuments(base_query_obj)

    if (page == 0) {
        let adminArticleList = await articleModel.find(admin_query_obj, {
                content: 0
            })
            .populate({
                path: `ratings`,
                select: 'date avatar like_num'
            })
            .populate({
                path: 'userInfo',
                select: 'avatar'
            }).sort({ '_id': -1 })
        searchResult.splice(0, 0, ...adminArticleList)
    }

    if (searchResult.length > 0) {
        res.send({
            code: 0,
            del: (req.session.userInfo && (req.session.userInfo.identity == 0)) || false,
            forumList: searchResult,
            total
        })
    } else {
        res.send({ code: 1, msg: '请求错误' })
    }
})

articleRouter.post('/delArticle', passport.authenticate('jwt', { session: false }), async(req, res) => {
    let { _id } = req.body

    let delStatus = await articleModel.remove({ _id })

    if (delStatus) {
        res.send({ code: 0, msg: '删除成功' })
    }
})

//获取文章详情页
articleRouter.get('/articleDetail/:id', async(req, res) => {
    let _id = req.params.id

    let classifyArr = 'null 精华 分享 问答 招聘'.split(' ')

    let lists = await articleModel.findOne({ _id }).populate({
        path: 'ratings',
        select: 'date avatar rating_txt author like_num like_lists',
        options: {
            sort: { _id: -1 }
        }
    }).populate({
        path: 'userInfo',
        select: 'avatar website nick_name sign date loginNum'
    })

    //改变每次访问次数 存储到数据库
    lists.readyNum = ++lists.readyNum

    //把这个值重新的存储起来
    await articleModel.updateOne({ _id }, { readyNum: lists.readyNum })

    //重新扩展了一个属性 
    lists.time = handleTime.distanceTime(lists.publishDate)

    //解析分类数字为文字
    lists.classify = classifyArr[lists.classify]

    //处理评论的时间
    lists.ratings.length > 0 && lists.ratings.forEach(item => {
        item.ratingsDate = handleTime.distanceTime(item.date)
    })

    //渲染这个页面  返回这个整理好的内容数据

    res.render('./pages/article.html', {
        lists,
        ...req.session.userInfo
    })
})

//添加评论处理
articleRouter.post('/ratings', passport.authenticate('jwt', { session: false }), async(req, res) => {
    let { article_id, rating_txt } = req.body
    let { nick_name, avatar } = req.user

    let insertResult = await ratingsModel.create({
        rating_txt,
        author: nick_name,
        avatar
    })
    let ratingsId = insertResult._id

    articleModel.findOne({ _id: article_id }, function(err, doc) {
        doc.ratings.push(ratingsId)
        doc.ratingUser.push(req.user._id)

        let r = doc.save()
        r.then(result => {
            res.send({ code: 0, msg: '发布成功' })
        })
    })

})

//点赞处理
articleRouter.post('/saveLike', passport.authenticate('jwt', { session: false }), async(req, res) => {
    let { _id, flag } = req.body

    let { like_num, like_lists } = await ratingsModel.findOne({ _id })

    flag == 'true' ? ++like_num : --like_num

    if (like_lists[req.user._id]) {
        delete like_lists[req.user._id]
    } else {
        like_lists[req.user._id] = true
    }

    let saveStatus = await ratingsModel.updateOne({ _id }, { like_num, like_lists })
    res.send(saveStatus)
})






module.exports = articleRouter